/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import fse from 'fs-extra';
import path from 'path';

import { BuildArtifactConst, BuildDirConst } from '../../const/build-directory-const.js';
import { CommonConst, DefaultTargetConst } from '../../const/common-const.js';
import { ModuleType } from '../../enum/module-type-enum.js';
import { ConfigJson } from '../../options/configure/config-json-options.js';
import { AbstractProcessResource } from '../abstract/abstract-process-resource.js';
import { TaskNames } from '../common/task-names.js';
import { ModuleTargetData } from '../data/hap-task-target-data.js';
import { TargetTaskService } from '../service/target-task-service.js';

import { getTaskRealName } from './hook/legacy-hook-compile-resource.js';
import LegacyFATask = TaskNames.LegacyFATask;
import fs from 'fs';

import { LegacyProcessOHPackageJson } from './har/legacy-process-oh-package-json.js';

const ohosTestTargetName = DefaultTargetConst.OHOS_TEST_TARGET;

/**
 * Fa 模型用于处理和生成用文件方式编译资源的中间文件
 *
 * @since 2022/9/8
 */
export class LegacyProcessResource extends AbstractProcessResource {
  constructor(taskService: TargetTaskService, entryModuleName?: string) {
    super(taskService, getTaskRealName(LegacyFATask.PROCESS_RESOURCE, entryModuleName));
    this.entryModuleName = entryModuleName;
    this.outputDir = path.resolve(this.pathInfo.getIntermediatesRes(), this.entryModuleName ?? '');
    this.resConfigFilePath = path.resolve(this.outputDir!, CommonConst.RES_CONFIG_FILE);
  }

  protected initTaskDependsForOtherModule() {
    this.featureAddEntryDpends();
  }

  initTaskDepends() {
    super.initTaskDepends();
    if (this.targetService.getTargetData().getModuleModel().isHarModule()) {
      this.declareDepends(LegacyProcessOHPackageJson.name);
    }
  }

  /**
   * Feature添加Entry依赖
   * FA模型 Feature模块依赖Entry模块资源编译完成
   *
   * @private
   */
  private featureAddEntryDpends(): void {
    if (this.service.getModuleModel().getModuleType() !== ModuleType.Feature) {
      return;
    }

    const relatedEntryModules = this.service.getRelatedEntryModules();
    if (relatedEntryModules === undefined) {
      return;
    }
    relatedEntryModules.forEach((entryName) => {
      const entryTargetData = this.targetData.findTargetDataByName(entryName);

      // ohosTest target不建立依赖关系
      if (!entryTargetData || this.targetName === ohosTestTargetName) {
        return;
      }
      const taskName = `${entryTargetData!.getTargetName()}@` + `${LegacyFATask.COMPILE_RESOURCE.name!}`;

      const entryTask = this.node.findModuleByName(entryName)?.getTaskByName(taskName);
      if (!entryTask) {
        return;
      }
      this.declareDepends(taskName, entryName);
    });
  }

  initCommandBuilder() {
    const configObj = this.moduleModel.getJsonObjByTargetName(this.targetName);
    const bundleName = (configObj as ConfigJson.ConfigOptObj).app.bundleName;
    this.restoolConfigBuilder
      .addJsonFile(this.processedJson!) // config.json文件
      .addModulePackName(bundleName) // bundleName
      .addOutputDir(this.outputDir!) // 输出目录
      .addResTable(path.resolve(this.getTaskTempDir(this.targetData, BuildDirConst.R), BuildArtifactConst.RESOURCE_TABLE_H));

    // HOS工程会单独传递HOS toolchain路径给restool
    if (!this.sdkInfo.isOhos) {
      const definedSysIdsPath = path.resolve(this.sdkInfo.getHosToolchainsDir(), 'id_defined.json');
      if (fs.existsSync(definedSysIdsPath)) {
        this.restoolConfigBuilder.addDefinedSysIds(definedSysIdsPath);
      }
    }

    if (this.targetData.getTargetName() === ohosTestTargetName) {
      // ohosTest资源编译时添加需要额外的编译的Resources
      this.addOhosTestExtraCompilationResources(this.restoolConfigBuilder);
    }
  }

  protected doTaskAction() {
    // feature资源编译时，需要依赖entry资源编译结果
    if (this.moduleModel.getModuleType() === ModuleType.Feature) {
      const entryCompileResource = this.getEntryCompileResouceDir(this.targetData, this.entryModuleName!);
      if (entryCompileResource && fse.existsSync(entryCompileResource)) {
        this.restoolConfigBuilder.addEntryCompiledResource(entryCompileResource);
      }
    }

    if (this.isEnabledIconCheck()) {
      // 资源编译图标检测
      this.restoolConfigBuilder.setIconCheck(true);
    }

    // 超纹理压缩性能优化,配置资源编译线程数写入resConfig, 用户没配置则不需要写入信息, 支持FA模型
    this.restoolConfigBuilder.setResCompileThread(this.processResCompileThreads());
    super.doTaskAction();
  }

  /**
   * 获取Entry模块资源编译结果目录
   *
   * @param {ModuleTargetData} targetData 模块target对象
   * @param {string} entryName entry模块名称
   * @private
   */
  private getEntryCompileResouceDir(targetData: ModuleTargetData, entryName: string): string | undefined {
    const entryTargetData = targetData.findTargetDataByName(entryName);
    return entryTargetData?.getPathInfo().getIntermediatesRes();
  }
}
